const {
    toUrl,
    msgLoading,
    globalData
} = getApp()
import {
    request
} from '@/utils/request'
Page({
    toUrl,
    data: {
        shareShow: false,
        globalData,
        current: 0,
        goods_id: 0,
        detail: null,
        cartShow: false,
        type: 'buy',
        goodsId: '',
        shopSpec: null,
        num: 1,
        currentSpec: null, //加入购物车时有规格时需要加入的规格参数
        store_count: '',
        itemType: 1,
        basePrice: '',
        headBc: '',
        act: '/img/act3.png',
        amount_total: '',
        poster: null
    },
    toUrlSub(options){
        console.log(options);
        let {url} = options.currentTarget.dataset
        wx.navigateTo({
          url: url,
        })
    },

    //秒杀商品分享
    handleShare() {
        if (this.data.detail.images.length == 0) {
            wx.showToast({
                title: '未上传商品图，请上传',
                icon: 'none'
            })
            return
        }
        this.shows()
    },
    shows: function () {
        // wx.showToast({
        //     title: '生成海报中...',
        //     icon: "loading",
        //     mask: true,
        // })
        this.setData({
            shareShow: true
        })


        wx.setPageStyle({
            style: {
                overflow: 'hidden'
            }
        })
        this.drawPoster()
    },
    drawPoster() {
        const query = wx.createSelectorQuery()
        const self = this;
        //...判断本地信息，引导用户授权获取头像部分

        query.select('#myCanvas')
            .fields({
                node: true,
                size: true
            })
            .exec(async (res) => {
                self.canvas = res[0].node
                self.ctx = self.canvas.getContext('2d')
                //屏幕像素比
                const dpr = wx.getSystemInfoSync().pixelRatio
                self.canvas.width = res[0].width * dpr
                self.canvas.height = res[0].height * dpr
                //画布放大后绘制比例也相应放大，这样绘图时就能按原尺寸计算
                self.ctx.scale(dpr, dpr)
                //...画布适配部分
                //背景
                self.ctx.fillStyle = '#fff'

                console.log(self.canvas.width, self.canvas.height);
                self.ctx.fillRect(0, 0, self.canvas.width, self.canvas.height)
                //...背景及文字绘制部分
                //文字
                self.ctx.textBaseline = 'top'
                self.ctx.textAlign = 'left'
                self.ctx.fillStyle = '#000'
                self.ctx.font = '16px  Helvertica'
                self.ctx.fillText("分享你一个好物", 10, 15)
                wx.showLoading({
                    title: '海报生成中'
                });
                //获取头像和二维码和背景图
                self.getBgImg()
                const result = await Promise.all([self.getQrcode(), self.getBgImg()]).catch((err) => {
                    console.log(err);
                })

                console.log(result);
                if (result == undefined) {
                    wx.showToast({
                        title: '未上传主图图片',
                        icon: 'none'
                    })
                    // wx.hideLoading()
                    setTimeout(() => {
                        self.setData({
                            shareShow: false
                        })
                    }, 1500);

                }
                await Promise.all([self.drawQRcode2(result[0]), self.drawBgImg(result[1]), self.drawTitle()])

                wx.hideLoading()
                // //将canvas转化成临时路径，用imge加载生成图片呈现在页面
                self.canvas2Img()
            })
    },

    canvas2Img() {
        const self = this
        console.log(55555);
        setTimeout(() => {
            //将画布保存成临时路径 供展示
            wx.canvasToTempFilePath({
                //因为是2d所以需要传入整个canvas节点
                canvas: self.canvas,
                success: (res) => {
                    //将路径保存下来通过image在页面上展示
                    console.log(res);
                    this.setData({
                        poster: res.tempFilePath
                    })
                    //   self.poster = 
                },
                fail: (res) => {
                    console.log(`fail`, res)
                }
            }, self)
        }, 200)
    },
    //获取小程序二维码
    getQrcode() {
        console.log(11122888);
        return new Promise((resolve, reject) => {
            let errorData = {
                code: 0,
                msg: '请求失败: 1.未上传主图图片;2.二维码绘制失败'
            }
            let successData = {
                code: 1,
                msg: '请求成功'
            }

            let pages = getCurrentPages() //获取加载的页面
            let currentPage = pages[pages.length - 1] //获取当前页面的对象
            let url = currentPage.route //当前页面url
            let options = currentPage.options //如果要获取url中所带的参数可以查看options
            let urlWithArgs = url + '?'
            for (let key in options) {
                let value = options[key]
                urlWithArgs += key + '=' + value + '&'
            }
            urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

            console.log(urlWithArgs);

            let data = {
                typeid: 1,
                scene: '?id=' + this.data.goodsId
            }
            request('currency/getwxacodeunlimit', {
                data
            }).then(res => {
                console.log(res);

                resolve(res.data.qrcode)

            }).catch((err) => {
                reject(errorData)
            })

        })
    },
    //计算文本超出超短函数
    getTextCt(str) {
        const self = this;
        console.log(self.canvas.width)
        let canvasWidth = self.canvas.width
        let fontSize = parseInt((wx.getSystemInfoSync().windowWidth / 375) * 30)
        let rowFontNum = Math.floor(canvasWidth / fontSize)
        let strLength = str.length
        let rows = Math.ceil(strLength / rowFontNum)
        return {
            canvasWidth,
            fontSize,
            rowFontNum,
            strLength,
            rows
        }
    },
    //绘制商品标题
    drawTitle() {
        const self = this;
        const dpr = wx.getSystemInfoSync().pixelRatio

        let height = self.canvas.height / dpr
        let chazhi = height - 100
        console.log(chazhi);
        // const context = wx.createCanvasContext('myCanvas')
        var text = this.data.detail.goods_name; //这是要绘制的文本
        // var text = '你好你好你好单独你好你好你好单独你好你好你好单独你好你好你好单独'; //这是要绘制的文本
        var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
        var temp = "";
        var row = [];
        let len = 0
        self.ctx.font = 'bold  14px Helvertica'

        self.ctx.fillStyle = '#000'

        for (var a = 0; a < chr.length; a++) {
            if (self.ctx.measureText(temp).width < 170) {
                temp += chr[a];
            } else {
                a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
                row.push(temp);
                temp = "";
            }
        }
        row.push(temp);

        //如果数组长度大于2 则截取前两个
        if (row.length > 2) {
            console.log(99999999);
            var rowCut = row.slice(0, 2);
            var rowPart = rowCut[1];
            var test = "";
            var empty = [];
            for (var a = 0; a < rowPart.length; a++) {
                if (self.ctx.measureText(test).width < 170) {
                    test += rowPart[a];
                } else {
                    break;
                }
            }
            empty.push(test);
            var group = empty[0] + "..." //这里只显示两行，超出的用...表示
            rowCut.splice(1, 1, group);
            row = rowCut;
        }
        console.log(row);
        if (row.length > 1) {
            len = 0
        } else {
            len = 10

        }
        for (var b = 0; b < row.length; b++) {
            self.ctx.fillText(row[b], 10, chazhi + 25 + b * 30 + len, 170);
        }
    },

    //绘制二维码图像
    drawQRcode2(bufferData) {
        const self = this;
        const dpr = wx.getSystemInfoSync().pixelRatio
        let wid = self.canvas.width / dpr
        let height = self.canvas.height / dpr
        let chazhi = height - 140

        return new Promise((resolve, reject) => {
            let image = self.canvas.createImage();
            //加载buffer数据
            image.src = bufferData;
            image.onload = () => {
                self.ctx.drawImage(image, wid - 90, chazhi + 50, 80, 80);
                resolve()
            }
        })
    },
    //绘制背景图
    drawBgImg(src) {
        const self = this;
        const dpr = wx.getSystemInfoSync().pixelRatio
        const width = self.canvas.width / dpr
        const height = self.canvas.height / dpr
        console.log(width, height);
        return new Promise((resolve, reject) => {
            let image = self.canvas.createImage();
            image.src = src;
            image.onload = (res) => {
                self.ctx.drawImage(image, 0, 40, width, height - 140);
                resolve()
            }

        })
    },
    //获取背景图
    getBgImg() {
        const self = this
        return new Promise((resolve, reject) => {
            let errorData = {
                code: 0,
                msg: '请求失败: 1.未上传主图图片;2.二维码绘制失败'
            }
            let successData = {
                code: 1,
                msg: '请求成功'
            }
            let imglist = self.data.detail.images
            if (imglist.length == 0) {
                // console.log(9999999);
                reject(errorData)
            } else {
                resolve(imglist[0], successData)
            }
            console.log(img1, '------');
            // if (condition) {

            // }
            // resolve
            //获取云存储中的图片
            //   self.getImgInfo('cloud://cloud1-8gp38tt58f1cad0e.636c-cloud1-8gp38tt58f1cad0e-1306912889/mdata/img/weiwuxian2.jpg').then(res=>{
            //     console.log(`cloudImg`,res)
            //     //{errMsg: "getImageInfo:ok", width: 794, height: 794, type: "jpeg", orientation: "up",path: "http://tmp/wsz3Rlfyo5yj279d60b79b9c747d19a192f79e7e9cb8.jpg",type:"jpeg",width:794}
            //     if(res && res.path){
            //       resolve(res.path)
            //     }else{
            //       reject()
            //     }
            //   })
        })
    },
    //处理头部滚动事件
    onPageScroll(e) {
        const scrollTop = e.scrollTop
        if (scrollTop > 150) {
            this.setData({
                headBc: 'headbc',
                act: '/image/icon-arrow-left.png'
            })
        } else {
            this.setData({
                headBc: '',
                act: '/img/act3.png'
            })
        }
    },
    //收藏
    handleCollesd() {
        const that = this
        const data = {
            goods_id: that.data.goodsId,
            typeid: that.data.detail.is_collect == 0 ? 1 : 2
        }
        request('stores/goodscollect', {
            show: true,
            data
        }).then(res => {
            that.getDetail()
        })
    },
    itemClick(e) {
        let {
            type
        } = e.currentTarget.dataset;

        this.setData({
            itemType: type
        })
    },
    //拨打电话
    makePhoneCall() {
        console.log(4444);
        wx.makePhoneCall({
            phoneNumber: this.data.detail.store.kefu
        })
    },
    cartShow({
        currentTarget
    }) {
        let detail1 = this.data.detail
        // detail1.buy_num  = 2
        // detail1.quota_num  = 3
        if (detail1.quota_num != 0) {
            if (detail1.buy_num >= detail1.quota_num) {
                wx.showToast({
                    title: `限购数量${detail1.quota_num}`,
                    icon: 'none'
                })
                return

            }
        }


        //打开的时候变成1
        this.setData({
            num: 1
        })
        const {
            type
        } = currentTarget.dataset
        if (type) {
            this.setData({
                type
            })
        }
        this.getGoodsItem().then(() => {
            //当存在规格时
            if (this.data.shopSpec && this.data.shopSpec.length > 0) {
                console.log(this.data.shopSpec)
                let item_id = ''
                this.data.shopSpec.forEach(item => {
                    if (!item_id) {
                        item_id = item.specitem[0].item_id
                    } else {
                        item_id = item_id + '_' + item.specitem[0].item_id
                    }
                })
                const that = this
                const data = {
                    item_id: item_id,
                    goods_id: this.data.detail.goods_id
                }
                request('stores/getspecgoods', {
                    data
                }).then(res => {
                    if (res.errcode == 1) {
                        const detail = that.data.detail
                        detail.price = res.data.price
                        const amount_total = Math.round(detail.price * 100 * this.data.num) / 100
                        that.setData({
                            amount_total: amount_total,
                            store_count: res.data.store_count,
                            detail: detail,
                            currentSpec: res.data.item_id
                        })
                    }
                })
            } else {
                const that = this
                const data = {
                    item_id: '',
                    goods_id: this.data.detail.goods_id
                }
                request('stores/getspecgoods', {
                    data
                }).then(res => {
                    if (res.errcode == 1) {
                        const detail = that.data.detail
                        detail.price = res.data.price
                        const amount_total = Math.round(detail.price * 100 * this.data.num) / 100
                        that.setData({
                            amount_total: amount_total,
                            store_count: res.data.store_count,
                            detail: detail,
                            currentSpec: res.data.item_id
                        })
                    }
                })
            }
            if (this.data.cartShow) {
                //弹窗关闭时，需要将num初始化为1
                this.setData({
                    cartShow: !this.data.cartShow,
                    num: 1
                })
            } else {
                this.setData({
                    cartShow: !this.data.cartShow
                })
            }

        })
    },
    changeSwiper({
        detail
    }) {
        const {
            current
        } = detail
        this.setData({
            current
        })
    },
    //减按钮
    delBtn() {
        if (this.data.store_count == 0) {
            wx.showToast({
                icon: 'none',
                title: '库存不足',
            })
            return
        }
        let num = this.data.num
        let amount_total = ''
        if (num === 1) {
            amount_total = Math.round(this.data.detail.price * 100 * num) / 100
            return
        } else {
            num = num - 1
            amount_total = Math.round(this.data.detail.price * 100 * num) / 100
        }
        this.setData({
            amount_total: amount_total,
            num: num
        })
    },
    //加按钮
    plusBtn() {

        if (this.data.detail.quota_num == this.data.num) {
            wx.showToast({
                icon: 'none',
                title: `限购${this.data.detail.quota_num}个`,
            })
            return
        }

        console.log(111);
        if (this.data.store_count == 0) {
            wx.showToast({
                icon: 'none',
                title: '库存不足',
            })
            return
        }
        const storeCount = this.data.store_count
        let num = this.data.num
        if (num >= storeCount) {
            const amount_total = Math.round(this.data.detail.price * 100 * num) / 100
            this.setData({
                num: storeCount,
                amount_total: amount_total
            })
            return
        }
        num += 1
        const amount_total = Math.round(this.data.detail.price * 100 * num) / 100
        this.setData({
            amount_total: amount_total,
            num: num
        })
    },
    //处理加入购物车和购买
    next() {
        let detail1 = this.data.detail
        this.data.num
        if (detail1.quota_num != 0) {
            if (detail1.buy_num >= detail1.quota_num) {
                wx.showToast({
                    icon: 'none',
                    title: `限购数量${detail1.quota_num}`,
                })
                return
            } else if (detail1.buy_num + this.data.num > detail1.quota_num) {
                wx.showToast({
                    icon: 'none',
                    title: `限购数量${detail1.quota_num},已购${detail1.buy_num}`,
                })
                return
            }
        }

        if (detail1.is_voucher == 1) {
            if (this.data.num > 1) {
                // wx.showToast({
                //   title: '该商品属于优惠券,数量限购一个',
                //   icon:'none'
                // })
                this.setData({
                    num: 1
                })
            }
        }

        if (this.data.store_count == 0) {
            console.log('库存不足')
            wx.showToast({
                icon: 'none',
                title: '库存不足',
                duration: 2000
            })
            return
        }
        if (this.data.type == 'cart') {
            const data = {
                goods_id: this.data.detail.goods_id,
                num: this.data.num
            }
            //处理存在规格的情况
            if (this.data.shopSpec) {
                data.item_id = this.data.currentSpec
            }
            request('cart/addcart', {
                data
            }).then(res => {
                if (res.errcode == 1) {
                    wx.showToast({
                        title: '加入购物车成功'
                    })
                    this.setData({
                        cartShow: false,
                        num: 1
                    })
                    this.getDetail()
                }
            })

        } else {
            const detail = this.data.detail
            this.setData({
                cartShow: false
            })
            wx.getStorage({
                key: "_userInfo",
                success: ({
                    data
                }) => {
                    wx.navigateTo({
                        url: '/pages/order/form?type=buy&goods_id=' + detail.goods_id + '&item_id=' + this.data.currentSpec + '&num=' + this.data.num
                    })
                },
                fail: (err) => {
                    console.log(err);
                    wx.navigateTo({
                        url: '/pages/login/login'
                    })
                }
            })



        }
    },
    //选择规格
    selSpec(e) {
        if (this.data.store_count == 0) {
            return
        }
        const index = e.currentTarget.dataset.index
        const specname = e.currentTarget.dataset.specname
        const shopSpec = this.data.shopSpec
        //找到当前点击的规格，并修改index
        const obj = shopSpec.find(item => {
            return item.specname == specname
        })
        obj.specIndex = index

        //获取规格,处理规划格式
        let specArr = null
        shopSpec.forEach(item => {
            const index = item.specIndex
            if (!specArr) {
                specArr = item.specitem[index].item_id
            } else {
                specArr = specArr + '_' + item.specitem[index].item_id
            }
        })
        this.getSpecPrice(specArr)
        this.setData({
            num: 1,
            shopSpec: shopSpec
        })
    },
    //获取规格价格
    getSpecPrice(spec) {
        const that = this
        const data = {
            goods_id: this.data.detail.goods_id,
            item_id: spec
        }
        request('stores/getspecgoods', {
            data
        }).then(res => {
            const detail = that.data.detail
            detail.price = res.data.price
            const amount_total = Math.round(detail.price * 100 * this.data.num) / 100
            that.setData({
                amount_total: amount_total,
                store_count: res.data.store_count,
                detail: detail,
                currentSpec: res.data.item_id
            })
        })
    },
    getDetail() {
        const that = this
        const data = {
            goods_id: this.data.goodsId || 7
        }
        request('stores/goodsinfo', {
            data
        }).then(res => {
            let contents
            let zhengze = new RegExp('<img', 'g')
            let zhengze1 = new RegExp('<p', 'g')
            contents = res.data.store.purchase_notes.replace(zhengze1, '<p style="width:100%;height:auto;display:block;margin:10px 0;" ')
            contents = contents.replace(zhengze, '<img style="width:100%;height:auto;display:block;" ')
            res.data.store.purchase_notes = contents
            that.setData({
                basePrice: res.data.price,
                detail: res.data
            })
        }).finally(() => {
            wx.hideLoading()
        })
    },
    //获取规格
    getGoodsItem() {
        const that = this
        const data = {
            goods_id: this.data.detail.goods_id
        }
        return request('stores/getgoodsitem', {
            data
        }).then(res => {
            let specItem = null
            //有返回值时获取规格，没有时为null
            if (res.data) {
                specItem = res.data
                specItem.forEach(item => {
                    item.specIndex = 0
                })
            }

            that.setData({
                shopSpec: specItem
            })
        })
    },

    onLoad(options) {
        msgLoading()
        let id = ''
        if (options.id == undefined) {
            id = decodeURIComponent(options.scene).split('?')[1].split('=')[1]
        } else {
            id = options.id
        }
        this.setData({
            goodsId: id
        })
    },
    toTop() {
        wx.pageScrollTo({
            scrollTop: 400,
            duration: 300
        })
    },
    toBottom() {
        console.log(99999);
        wx.pageScrollTo({
            // scrollTop: 10000,
            offsetTop: -80,
            selector: '.gmxz_box',
            duration: 300
        })
    },

    onShow() {
        this.getDetail()
    },
})